<template>
  <div class="chatBox">
    <div id="we_chat_box" ref="wechatbox"> </div>
  </div>
</template>
<script lang="ts" setup>
import * as ww from '@wecom/jssdk'
import * as WeComApiConfigApi from '@/api/wecom/apiconfig'
import weComConfig from '@/utils/weComConfig'

const props = defineProps({
  msgMap: {
    type: Array
  }
})
const jsapiSignature = ref(null)
const formData = ref(null)
onMounted(() => {
  getWeComApiConfig()
})
const getWeComApiConfig = async () => {
  try {
    formData.value = await WeComApiConfigApi.getWeComApiConfig()
    jsapiSignature.value = await WeComApiConfigApi.getJsapiSignature({
      url: window.location.href
    })
    initComponentSession()
  } finally {
  }
}
const getAgentConfigSignature = async () => {
  return ww.getSignature(jsapiSignature.value.jsapiTicket)
}
const initComponentSession = async () => {
  try {
    ww.register({
      corpId: formData.value.corpId,
      agentId: formData.value.agentId,
      jsApiList: ['selectExternalContact', 'shareAppMessage', 'wwapp.invokeJsApiByCallInfo'],
      getAgentConfigSignature
    })
  } catch {}
  // 会话组件需要确保 WWOpenData 初始化成功
  await ww.initOpenData()
}
const factory = ww.createOpenDataFrameFactory()
const wechatbox = ref(null)

const emit = defineEmits(['setIsLogin', 'getPage', 'setLoading'])

const instance = ref(null)
const updateValue = ref()
const updateData = (val) => {
  updateValue.value = val
  if (instance.value) {
    instance.value.setData({
      list: []
    })
    setTimeout(() => {
      instance.value.setData({
        list: updateValue.value
      })
      emit('setLoading', false)
    }, 5e2)
  } else {
    createdComponentDisplay()
    emit('setLoading', false)
  }
}
const createdComponentDisplay = () => {
  if (wechatbox.value) {
    wechatbox.value.innerHTML = ''
  }
  instance.value = factory.createOpenDataFrame({
    el: wechatbox.value,
    template: `
    <scroll-view scroll-y="{{true}}" scroll-top="{{data.scrollTop}}" bindscrolltoupper="scrolltoupper" upper-threshold="{{data.threshold}}" class="scrollCompany">
      <view
        wx:for="{{data.list}}"
        wx:key="msgid"
        class="msg {{item.senderType==1||item.senderType==3?'flexEnd':'flexStart'}}"
        data-index="{{index}}"
      >
        <view class="txtFont">[{{item.weComeName}}] {{item.sendTime}}</view>
        <ww-open-message
          class="custom-open-message {{item.senderType==1||item.senderType==3?'activeRight':'activeLeft'}}"
          message-id="{{item.msgid}}"
          secret-key="{{item.secureKey}}"
          open-type="viewMessage"
        />
      </view>
    </scroll-view>
   `,
    style: `
    .scrollCompany{
      height:100%;
    }
    .msg {
      padding:10px;
      padding-top: 20px;
      display:flex;
      flex-direction:column;
    }
    .flexEnd{
      align-items:flex-end;
    }
    .flexStart{
      align-items:flex-start;
    }
    .txtFont{
      font-size:12px;
      margin-bottom:6px;
      color:#494a4d;
    }
    .custom-open-message{
      padding-top: 20px;
      padding: 10px;
      border-radius: 4px;
    }
    .activeRight{
       background: #b3d4ff;
       display: inline-block;
    }
    .activeLeft{
      background: #ebecf0;
      display: inline-block;
    }
  `,
    error: (err) => {
      console.error('Error occurred:', err)
      if (err.errMsg == 'Missing open sid') {
        emit('setIsLogin', false)
      }
    },
    data: {
      list: updateValue.value,
      threshold: 20,
      scrollTop: 0
    },
    methods: {
      scrolltoupper() {
        emit('getPage')
      }
    }
  })
}
defineExpose({ updateData })
</script>
<style scoped lang="scss">
.chatBox {
  width: 100%;
  height: 100%;
  flex: 2;
  border-left: 1px solid #ececec;
  border-right: 1px solid #ececec;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  background: #f6f6f7;
}
::v-deep #we_chat_box {
  height: 100%;
  iframe {
    width: 100%;
    height: 100%;
    background: #f4f5f7;

    &::-webkit-scrollbar {
      width: 2px;
    }
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
    }
    &::-webkit-scrollbar-thumb {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:horizontal:start {
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
    }
    &::-webkit-scrollbar-thumb:horizontal:end {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }
}
</style>
